package com.tonann.app.utils;

import com.alibaba.fastjson2.JSONArray;
import com.tonann.app.domain.AppDevice;
import com.tonann.common.constant.CacheConstants;
import com.tonann.common.core.redis.RedisCache;
import com.tonann.common.utils.StringUtils;
import com.tonann.common.utils.spring.SpringUtils;

import java.util.Collection;
import java.util.List;

/**
 * 设备工具类
 *
 * @author ruoyi
 */
public class DeviceUtils {
    /**
     * 分隔符
     */
    public static final String SEPARATOR = ",";

    /**
     * 设置设备缓存
     *
     * @param key        参数键
     * @param deviceList 设备数据列表
     */
    public static void setDeviceCache(String key, List<AppDevice> deviceList) {
        SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), deviceList);
    }

    /**
     * 获取设备缓存
     *
     * @param key 参数键
     * @return deviceList 设备数据列表
     */
    public static List<AppDevice> getDeviceCache(String key) {
        JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
        if (StringUtils.isNotNull(arrayCache)) {
            return arrayCache.toList(AppDevice.class);
        }
        return null;
    }

    /**
     * 根据设备ID获取设备
     *
     * @param deviceId 设备ID
     * @return 设备
     */
    public static AppDevice getDeviceByDeviceId(Long deviceId) {
        AppDevice appDevice = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey("deviceId:") + deviceId);
        if (StringUtils.isNotNull(appDevice)) {
            return appDevice;
        }
        return null;
    }

    public static void setDeviceByDeviceId(AppDevice appDevice) {
        SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey("deviceId:") + appDevice.getDeviceId(), appDevice);
    }

    /**
     * 删除指定设备缓存
     *
     * @param key 设备键
     */
    public static void removeDeviceCache(String key) {
        SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey("deviceId:") + key);
    }

    /**
     * 清空设备缓存
     */
    public static void clearDeviceCache() {
        Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(CacheConstants.APP_DEVICE_KEY + "*");
        SpringUtils.getBean(RedisCache.class).deleteObject(keys);
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getCacheKey(String configKey) {
        return CacheConstants.APP_DEVICE_KEY + configKey;
    }
}
